package com.example.java_doc_search.controller;

import com.example.java_doc_search.seacher.DocSearch;
import com.example.java_doc_search.seacher.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@ResponseBody
public class DocSearcherController {
    private static DocSearch searcher = new DocSearch();
    // 需要把 json 转成 String类型
    private ObjectMapper objectMapper = new ObjectMapper();

    // 参数是查询词，返回结果是响应
    @RequestMapping(value = "/searcher",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String searcher(@RequestParam("query") String query) throws JsonProcessingException {
        // 参数 query 是来自于 ajax 中 url的query String 中 query 这个key的值
        List<Result> results = searcher.search(query);
        return objectMapper.writeValueAsString(results);// 返回转换成为 String 类型
    }
}
